<?php
namespace App\Lib;

use App\Lib\ParseXml;
use Symfony\Component\DomCrawler\Crawler;

class XmlToHtml
{
	private $parser;
	function __construct($xmlPath, $htmlDir)
	{
		// $crawler = new Crawler();
		$xmlPath = '/var/www/laravel/zk/public/uploads/xml_html/1/1.xml';
		// $crawler->addXmlContent(file_get_contents($xmlPath));


		// print_r($crawler->filterXPath('//journal-meta/publisher/publisher-name')->text());exit;
		// print_r($crawler->filter('mml|math')->getNode(0)->attributes);exit;
		// foreach ($crawler->filter('mml|math')->getNode(0)->attributes as $value) {
		// 	print_r($value->nodeValue);exit;
		// }

		// $parser = simplexml_load_file($xmlPath);
		// print_r($this->objectsIntoArray($parser));exit;

		// var_dump($parser->xpath('//body/sec[@id="sec1-molecules-23-02612"]'));exit;
		$parser = $this->parser = new ParseXml($xmlPath);
		// print_r($parser->getFigHtmlString());exit;
		// print_r($parser->getBody());exit;
		// print_r($parser->getBack());exit;


		echo <<<EOF
<!DOCTYPE html>
<html>
<head>
  <title>{$parser->publisher} | {$parser->article_title}</title>
  <link rel="stylesheet" type="text/css" href="./css/jquery-ui.min.css">
  <link rel="stylesheet" type="text/css" href="./css/magnific-popup.css">
  <link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
<body>
<div class="container-fluid">
<aside>
  <ul id="side-bar">{$this->getAside()}</ul>
</aside>
<article>
  <header>
    <div id="article-bar"><p><i>{$parser->journal_name}</i> <b>{$parser->publish_year}</b>, <i>{$parser->volume}</i>({$parser->issue}), {$parser->elocation_id}; doi:<a href="http://dx.doi.org/{$parser->doi}" target="_blank">{$parser->doi}</a></p>
    </div>
    <div id="article-type">{$parser->article_type}</div>
    <div id="article-title">{$parser->article_title}</div>
    <div id="article-authors">{$this->getAuthorString()}</div>
    <div id="article-affs">{$this->getAffs()}</div>
    <div id="article-author-notes">{$this->getAuthorNotes()}</div>
    <div id="article-history">{$this->getHistroy()}</div>
    <div id="article-abstract">
    	<h2>Abstract:</h2>
    	<div class="abstract-info">{$parser->abstract}</div>
    </div>
    <div id="article-keywords">
        <div class="label d-inline">Keywords:</div>	
        <div class="kewords d-inline">{$this->getKeywords()}</div>
    </div>
  </header>
  {$parser->getBody()}
  {$parser->getBack()}
</article>
</div>
<script src="./js/jquery.min.js"></script>
<script src="./js/jquery-ui.min.js"></script>
<script src="./js/jquery.magnific-popup.min.js"></script>
<script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async>
</script>
<script type="text/javascript">
$(function() {
  $(document).on('click', '.section-a,.a-xref-bibr', function (event) {
      event.preventDefault();
      $('html, body').animate({
          scrollTop: $($.attr(this, 'href')).offset().top
      }, 500);

  });

  var delay = function(ms, func) {
    return setTimeout(func, ms);
  };

  $('.a-xref-bibr').each(function() {
    var _this = $(this);
    _this.attr('title', '');
    var content = $("#" + _this.data('rid')).html();
    _this.tooltip({
      hide: { delay: 1000 },
      show: { effect: "blind", duration: 800 },
      content: content,
      position: { my: "left+15 center", at: "right center" }
    });
  });

  $('.html-popup').magnificPopup({
    type: 'inline',
    midClick: true,
    callbacks: {
      // elementParse: function(item) {
      //   return delay(10, function() {
      //     var _item_src, popup_height, windowHeight;
      //     _item_src = $("" + item.src);
      //     windowHeight = $(window).height() - 100;
      //     _item_src.css('height', "auto");
      //     popup_height = _item_src.height();
      //     if (popup_height && popup_height > windowHeight) {
      //       return _item_src.css('height', windowHeight + "px");
      //     }
      //   });
      // },
      open: function() {
        // return $('.html-front').before($('.mfp-wrap'));
      }
    }
  });
});
</script>
</body>
</html>
EOF;

exit;
	}

	private function getKeywords()
	{
		return implode('; ', $this->parser->keywords);
	}

	private function getHistroy()
	{
		return 'Received: ' . date('j F Y', strtotime($this->parser->received_date)) . ' / Accepted: ' . date('j F Y', strtotime($this->parser->accepted_date)) . ' / Published: ' . date('j F Y', strtotime($this->parser->publish_date));
	}

	private function getAuthorNotes()
	{
		$notes = $this->parser->getAuthorNotes();
		$html = '';
		foreach ($notes as $note) {
			$html .= '<div class="aff_item"><div class="aff_label d-inline"><sup>' . (($note['label'] == 'no') ? '' : $note['label']) . '<sup></div><div class="aff_content d-inline">' . $note['info'] . '</div></div>';
		}
		return $html;
	}

	private function getAffs()
	{
		$affs = $this->parser->getAffs();
		$html = '';
		foreach ($affs as $aff) {
			$html .= '<div class="aff_item"><div class="aff_label d-inline"><sup>' . (($aff['label'] == 'no') ? '' : $aff['label']) . '<sup></div><div class="aff_content d-inline">' . $aff['info'] . '</div></div>';
		}
		return $html;
	}

	private function getAside() {
		$sections = $this->parser->getSectionsByNode();
		$html = '';
		foreach ($sections as $section) {
			$children = $section['children'];
			$html .= '<li class="side-li"><a class="section-a" href="#'. $section['id'] . '" date-sec-type="' . $section['sec-type'] . '">' . $section['title'] . '</a></li>';
			if (!empty($children)) {
				$html .= '<ul class="side-sub-ul">';
				foreach ($children as $child) {
					$html .= '<li class="side-li"><a class="section-a" href="#'. $child['id'] . '" date-sec-type="' . $child['sec-type'] . '">' . $child['title'] . '</a></li>';
				}
				$html .= '</ul>';
			}
		}

		return $html;
	} 

	private function getAuthorString()
	{
		$as = '';
		$authors = $this->parser->getAuthors();

		foreach ($authors as $key => $author) {
			$as .= '<span class="sg_author"><a class="author_name">' . $author['name'] . '</a><sup>' . implode(',', $author['affs']) . '</sup>' . (($key+1 < count($authors)) ? ', ' : '') . '</span>';
		}

		return $as;

	}

	private function objectsIntoArray($arrObjData, $arrSkipIndices = array())
	{
	    $arrData = array();
	    
	    // if input is object, convert into array
	    if (is_object($arrObjData)) {
	        $arrObjData = get_object_vars($arrObjData);
	    }
	    
	    if (is_array($arrObjData)) {
	        foreach ($arrObjData as $index => $value) {
	            if (is_object($value) || is_array($value)) {
	                $value = $this->objectsIntoArray($value, $arrSkipIndices); // recursive call
	            }
	            if (in_array($index, $arrSkipIndices)) {
	                continue;
	            }
	            $arrData[$index] = $value;
	        }
	    }
	    return $arrData;
	}
}